package com.aaa.imports;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.WorkbookUtil;
import com.aaa.entity.TestUser;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author : luoBo
 */

@RestController
@RequestMapping("/testImport")
public class TestImport {


    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public void test(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {

        //1、校验文件格式
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)) {
            throw new RuntimeException("文件为空");
        }
        if (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx")) {
            throw new RuntimeException("文件格式错误");
        }
        //2、校验表头
        Workbook book = WorkbookUtil.createBook(file.getInputStream());
        String[] titleNames = {"用户", "密码"};
        Sheet sheetAt = book.getSheetAt(0);
        Row row = sheetAt.getRow(0);
        int cellNum = row.getPhysicalNumberOfCells();
        if (titleNames.length != cellNum) {
            throw new RuntimeException("表头错误");
        }
        for (int i = 0; i < titleNames.length; i++) {
            String titleName = titleNames[i];
            Cell cell = row.getCell(i);
            if (!titleName.equals(cell.getStringCellValue())) {
                throw new RuntimeException("表头错误");
            }
        }
        int rows = sheetAt.getPhysicalNumberOfRows();
        List<TestUser> userErrorList = new ArrayList<>();
        List<TestUser> userTrueList = new ArrayList<>();
        for (int i = 1; i < rows; i++) {
            TestUser testUser = new TestUser();
            Row rowFieldRow = sheetAt.getRow(i);
            Cell cell1 = rowFieldRow.getCell(0);
            Cell cell2 = rowFieldRow.getCell(1);
            testUser.setUsername(cell1.getStringCellValue());
            testUser.setPassword(String.valueOf(cell2.getNumericCellValue()));
            if ("admin".equals(testUser.getUsername()) && "123456".equals(testUser.getPassword())) {
                userTrueList.add(testUser);
            }
            StringBuffer errorMessage = new StringBuffer();
            if (!"admin".equals(testUser.getUsername())) {
                errorMessage.append("账号错误,");
            }
            if (!"123456".equals(testUser.getPassword())) {
                errorMessage.append("密码错误,");
            }
            if (errorMessage.length()>0){
                testUser.setErrorMessage(errorMessage.toString());
                userErrorList.add(testUser);
            }
        }
        List<TestUser> exportVOList = userErrorList;
        exportVOList = CollectionUtil.isNotEmpty(exportVOList) ? exportVOList : new ArrayList<>();
        try {
            // 1. 创建工作簿和工作表
            Workbook workbook = new XSSFWorkbook(); // 使用 XSSFWorkbook 生成 .xlsx 文件
            Sheet sheet = workbook.createSheet("分配信息");
            // 2. 创建表头
            String[] headers = {
                    "用户", "密码","错误信息"
            };
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            // 3. 填充数据
            int rowNumErr = 1;
            for (TestUser vo : exportVOList) {
                Row rowErr = sheet.createRow(rowNumErr++);
                rowErr.createCell(0).setCellValue(vo.getUsername());
                rowErr.createCell(1).setCellValue(vo.getPassword());
                rowErr.createCell(2).setCellValue(vo.getErrorMessage());
            }
            //错误的导出
            String uuid = UUID.randomUUID().toString();
            FileOutputStream outputStream = new FileOutputStream("D:/templates/"+uuid+".xlsx");
            workbook.write(outputStream);
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }
    
    //3、校验数据，把不对的数据放入errorList中，正确的数据放入数据库中

    //4、错误数据存excel放一个地址中，返回错误地址
    @GetMapping("/download/{templateName}")
    public void download(@PathVariable(value = "templateName")String templateName,HttpServletResponse response) throws Exception {

        FileInputStream fileInputStream = new FileInputStream("D:/templates/" + templateName);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("古法单件调拨码表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
        byte[] bytes = new byte[1024];
        int len = 0;
        ServletOutputStream outputStream = response.getOutputStream();
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.close();
        fileInputStream.close();
    }
}
